<template>
  <div class="login">
    <div class="title">登陆页</div>
    <van-form @submit="login">
      <van-field
        class="input-box"
        v-model="formData.phone"
        placeholder="输入手机号"
        :rules="[{ required: true, pattern:/^1[3-9]\d{9}$/, message: '请输入手机号' }]"
      />
      <van-field
        class="input-box"
        v-model="formData.pass"
        type="password"
        placeholder="输入密码"
        :rules="[{ required: true, pattern:/^\d{4}$/, message: '请输入密码' }]"
      />
      <div style="margin: 16px;" class="dl1">
        <van-button round block type="info" native-type="submit" >登陆</van-button>
      </div>
    </van-form>
    
  </div>
</template>

<script>

import { Toast } from 'vant';
import {user_login} from '../utils/api'

export default {
  data(){
    return {
      formData:{
        phone:'',
        pass:''
      }
    }
  },
  methods:{
    login(){
      //发起登陆请求
      user_login( this.formData ).then((res)=>{
        if( res.data.code == 200 ){
          //保存用户信息,token
          localStorage.setItem('token',res.data.token);
          localStorage.setItem('userinfo', JSON.stringify( res.data.userinfo ) );
          
        // 请求vuex中的当前用户的收藏列表
        this.$store.dispatch('shop_favlist');

        // 调用vuex中的异步方法，请求当前用户的购物车列表
          this.$store.dispatch('request_shopcartlist');
          
          //自动跳转到首页
          this.$router.push('/');
       
          Toast.success('登陆成功!')
        }else{
          Toast.fail('登陆失败!')
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped> 
.login{
  margin: 50px 20px;
}
.login .title{
  font-weight: bold;
  text-align: center;
  line-height: 40px;
}


.login .input-box{
  border: 1px solid #ccc;
  margin: 30px 0;
  border-radius: 30px;
}

</style>